package com.demo.petshop.controller;

import com.demo.petshop.entity.Users;
import com.demo.petshop.mapper.UsersMapper;
import com.demo.petshop.service.UsersService;
import com.demo.petshop.service.impl.LoginUser;
import com.demo.petshop.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 *  控制层。
 *
 * @author lenovo
 * @since 2025-06-11
 */
@RestController
@RequestMapping("/users")
public class UsersController {

    @Autowired
    private UsersService usersService;

    @Autowired
    private UsersMapper usersMapper;

    private int getUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        return loginUser.getUser().getUserId();
    }

    @PostMapping("login")
    public Object login(@RequestBody Users users){
        return usersService.login(users);
    }

    @PostMapping("loginAdmin")
    public Object loginAdmin(@RequestBody Users users){
        return usersService.loginAdmin(users);
    }

    @GetMapping("checkMemberLevel")
    public Object checkMemberLevel(){
        return usersService.checkMemberLevel();
    }

    @PostMapping("register")
    public Object register(@RequestBody Users user){
        return usersService.register(user);
    }
    @PostMapping("registerShopkeeper")
    public Object registerShopkeeper(@RequestBody Users user){
        return usersService.registerShopkeeper(user);
    }
    @PostMapping("password")
    public Object forgotPassword(@RequestBody Map<String, Object> passwordData){
        return usersService.updatePassword(passwordData);
    }

    @GetMapping("profile")
    public Result getProfile(@RequestParam Integer userId){
        return Result.success(usersService.getProfile(userId));
    }

    @GetMapping("profileNoId")
    public Result profile(){
        return Result.success(usersService.getProfile(getUserId()));
    }

    @PostMapping("updateprofile")
    public Result updateprofile(@RequestBody Users users){
            return Result.success(usersService.updateprofile(users));
    }
    @PostMapping("settings")
    public Result updateSettings(@RequestBody Map<String, Object> settingsData){
        return Result.success(usersService.updateSettings(settingsData));
    }
    @GetMapping("checkLogin")
    public Object checkLog(){
        return usersService.checkLog();
    }

    @GetMapping("stats")
    public Object stats(){
        return usersService.stats();
    }

    @GetMapping("list")
    public Object list(){
        return Result.success(usersService.list());
    }
    @PostMapping("clear-cache")
    public Object clearCache(){
        return Result.success(true);
    }
}
